package cn.com.blueInfo.HaiYuan.business.journal.service.impl;

import cn.com.blueInfo.HaiYuan.business.journal.entity.JournalBase;
import cn.com.blueInfo.HaiYuan.business.journal.mapper.JournalBaseMapper;
import cn.com.blueInfo.HaiYuan.business.journal.service.JournalBaseService;
import cn.com.blueInfo.utils.result.BootstrapTable;
import cn.com.blueInfo.utils.result.ResultInfo;
import cn.com.blueInfo.utils.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 日记账基本信息接口服务具体实现
 * @ClassName: JournalBaseServiceImpl
 * @author suxch
 * @date 2020年9月25日  上午10:18:56
 */
@Log4j2
@Service
public class JournalBaseServiceImpl implements JournalBaseService {

    @Autowired
    private JournalBaseMapper journalMapper;

    /**
     * 分页查询日记账基本数据具体实现
     * @Title: queryJournalBaseDataByPage
     * @param request
     * @return BootstrapTable
     */
    @Override
    public BootstrapTable queryJournalBaseDataByPage(HttpServletRequest request) {
        BootstrapTable result = new BootstrapTable();
        JSONObject param = RequestPayload.analysis(request);
        log.info("bootstrapTable请求参数" + param);

        Map<String, Object> paramMap = JSON.parseObject(param.toJSONString());
        if (paramMap.get("recordDate1") != null) {
            String recordDate = paramMap.get("recordDate1").toString();
            String days = recordDate.substring(recordDate.lastIndexOf("-"));
            String startDate = DateUtil.addOrCutDownForDay(Integer.parseInt(days));
            String endDate = DateUtil.getFormatDate(new Date());
            paramMap.put("startRecordDate", startDate);
            paramMap.put("endRecordDate", endDate);
        }
        if (paramMap.get("recordDate2") != null) {
            String recordDate = paramMap.get("recordDate2").toString();
            paramMap.put("recordDate", recordDate + "%");
        }
        try {
            Integer count = journalMapper.queryJournalBaseInfoCount(paramMap);
            List<JournalBase> drugsBaseList = journalMapper.queryJournalBaseInfo(paramMap);
            result.setTotal(count);
            result.setRows(drugsBaseList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            result.setTotal(0);
            result.setRows(null);
        }
        return result;
    }

    /**
     * 新增日记账基本信息具体实现
     * @Title: addJournalBaseData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo addJournalBaseData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestParam = request.getParameter("requestParam");

        if (JSONUtil.isToJSONObject(requestParam)) {
            JournalBase journalBase = JSON.parseObject(requestParam, JournalBase.class);
            journalBase.setSystemTime(DateUtil.getFormatDateTime(new Date()));
            journalBase.setUnid(UUIDUtil.createUNID());
            journalBase.setAddUser(request.getParameter("userInfo"));
            try {
                Integer count = journalMapper.addJournalBaseInfo(journalBase);
                if (count == 0) {
                    result.setResult(false);
                    result.setMessage("添加失败，请联系管理员");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                result.setResult(false);
                result.setMessage("添加失败，请联系管理员");
            }
        }
        return result;
    }

    /**
     * 更新日记账基本信息具体实现
     * @Title: replaceJournalBaseInfo
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo replaceJournalBaseInfo(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestParam = request.getParameter("requestParam");

        if (JSONUtil.isToJSONObject(requestParam)) {
            JournalBase journalBase = JSON.parseObject(requestParam, JournalBase.class);
            journalBase.setModifyTime(DateUtil.getFormatDateTime(new Date()));
            journalBase.setModifyUser(request.getParameter("userInfo"));
            try {
                Integer count = journalMapper.updateJournalBaseInfoByUnid(journalBase);
                if (count == 0) {
                    result.setResult(false);
                    result.setMessage("更新失败，请联系管理员");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                result.setResult(false);
                result.setMessage("更新失败，请联系管理员");
            }
        }
        return result;
    }

    /**
     * 删除日记账基本信息具体实现
     * @Title: removeJournalBaseInfo
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo removeJournalBaseInfo(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String currUnid = request.getParameter("unid");
        try {
            Integer count = journalMapper.delJournalBaseInfoByUnid(currUnid);
            if (count == 0) {
                result.setResult(false);
                result.setMessage("删除失败，请联系管理员");
            } else {
                result.setMessage("数据删除成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setResult(false);
            result.setMessage("删除失败，请联系管理员");
        }
        return result;
    }

    /**
     * 查询合计日记账基本信息具体实现
     * @Title: querySumJournalBaseInfo
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo querySumJournalBaseInfo(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestData = request.getParameter("requestParam");
        if (JSONUtil.isToJSONObject(requestData)) {
            Map<String, Object> paramMap = JSON.parseObject(requestData);
            try {
                JSONArray resultData = journalMapper.queryJournalBaseSumInfo(paramMap);
                result.setData(resultData);
            } catch (Exception e) {
                log.error(e.getMessage());
                result.setResult(false);
                result.setMessage("查询失败，请联系管理员");
            }
        }
        return result;
    }

    /**
     * 导出Excel文件具体实现
     * @Title: exportExcelFile
     * @param request
     * @param response
     */
    @Override
    public void exportExcelFile(HttpServletRequest request, HttpServletResponse response) {
        String requestParam = request.getParameter("requestParam");
        JSONArray journalData = null;
        if (JSONUtil.isToJSONObject(requestParam)) {
            Map<String, Object> paramMap = JSON.parseObject(requestParam);

            try {
                List<JournalBase> journalBaseList = journalMapper.exportJournalBaseInfo(paramMap);
                journalData = JSON.parseArray(JSON.toJSONString(journalBaseList));
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        Map<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("type", "收支类型");
        headMap.put("items", "收支项目");
        headMap.put("money", "金额");
        headMap.put("recordDate", "记录日期");
        headMap.put("content", "内容");
        headMap.put("remarks", "备注");

        String title = "日记账基本信息";

        ExcelUtil.downloadExcelFile(title, headMap, journalData, response);
    }

    /**
     * 查询月份数据具体实现
     * @Title: queryMonthData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo queryMonthData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();

        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("first", "first");
            JSONArray resultData = journalMapper.queryJournalBaseDateInfo(paramMap);
            result.setData(resultData);
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setResult(false);
            result.setMessage("查询失败，请联系管理员");
        }
        return result;
    }

    /**
     * 添加上月结余数据具体实现
     * @Title: addLastMonthBalanceData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo addLastMonthBalanceData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestParam = request.getParameter("requestParam");
        if (JSONUtil.isToJSONObject(requestParam)) {
            JSONObject requestData = JSON.parseObject(requestParam);
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("record", requestData.getString("lastMonth"));
            paramMap.put("accountCard", requestData.getString("accountCard"));

            try {
                JSONArray lastMonthInfo = journalMapper.queryLastMonthBalanceInfo(paramMap);
                JournalBase journal = new JournalBase();
                if (!lastMonthInfo.isEmpty()) {
                    JSONObject lastMonth = lastMonthInfo.getJSONObject(0);
                    journal.setUnid(requestData.getString("lastMonth") + "_" + requestData.getString("accountCard") + "_结余信息");
                    journal.setType("income");
                    journal.setMoney(lastMonth.getBigDecimal("money"));
                    journal.setAccountCard(requestData.getString("accountCard"));
                    journal.setRecordDate(requestData.getString("currMonth"));
                    journal.setContent("系统生成结余信息");
                    journal.setAddUser("管理员 : admin");
                    journal.setDomainCode("HAIYUAN");
                    journal.setApplicationCode("haiyuan");
                    journal.setStatus("3");
                }

                paramMap.clear();
                paramMap.put("unid", journal.getUnid());
                Integer balanceCount = journalMapper.queryJournalBaseInfoCount(paramMap);
                if (balanceCount != 0) {
                    journal.setModifyTime(DateUtil.getFormatDateTime(new Date()));
                    Integer replace = journalMapper.updateJournalBaseInfoByUnid(journal);
                    if (replace == 1) {
                        result.setResult(true);
                        result.setMessage("上月月结信息更新成功");
                    } else {
                        result.setResult(false);
                        result.setMessage("上月月结信息更新失败，请联系管理员");
                    }
                } else {
                    journal.setSystemTime(DateUtil.getFormatDateTime(new Date()));
                    Integer add = journalMapper.addJournalBaseInfo(journal);
                    if (add == 1) {
                        result.setResult(true);
                        result.setMessage("上月月结信息生成成功");
                    } else {
                        result.setResult(false);
                        result.setMessage("上月月结信息生成失败，请联系管理员");
                    }
                }

            } catch (Exception e) {
                log.error(e.getMessage());
                result.setResult(false);
                result.setMessage("月结信息生成更新过程出错，请联系管理员");
            }
        }
        return result;
    }

    /**
     * 获取分类汇总的日期数据具体实现
     * @Title: querySumDateData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo querySumDateData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String yearInfo = request.getParameter("yearInfo");
        String monthInfo = request.getParameter("monthInfo");
        String accountCard = request.getParameter("accountCard");
        List<String> dataList = null;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (accountCard != null && !"".equals(accountCard))
                paramMap.put("accountCard", accountCard);

            if (yearInfo != null) {
                paramMap.put("recordDate", yearInfo);
                dataList = journalMapper.querySumMonthInfo(paramMap);
            } else if (monthInfo != null) {
                paramMap.put("recordDate", monthInfo);
                dataList = journalMapper.querySumDaysInfo(paramMap);
            } else {
                dataList = journalMapper.querySumYearsInfo(paramMap);
            }
            if (dataList != null && !dataList.isEmpty()) {
                result.setData(dataList);
            } else {
                result.setResult(false);
                result.setMessage("未获取到日期数据，请联系管理员");
            }
        } catch (Exception e) {
            result.setResult(false);
            result.setMessage("获取日期数据出错，请联系管理员");
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 查询分类汇总数据具体实现
     * @Title: queryItemsSumData
     * @param request
     * @return BootstrapTable
     */
    @Override
    public BootstrapTable queryItemsSumData(HttpServletRequest request) {
        BootstrapTable result = new BootstrapTable();
        JSONObject param = RequestPayload.analysis(request);
        log.info("bootstrapTable请求参数" + param);

        Map<String, Object> paramMap = JSON.parseObject(param.toJSONString());
        if (paramMap.get("recordDate") != null) {
            String recordDate = paramMap.get("recordDate").toString();
            if (recordDate.length() == 4) paramMap.put("dateType", "year");
            if (recordDate.length() == 7) paramMap.put("dateType", "month");
            if (recordDate.length() == 10) paramMap.put("dateType", "day");
        }
        try {
            Integer count = journalMapper.queryItemsSumInfoCount(paramMap);
            JSONArray itemsSumList = journalMapper.queryItemsSumInfo(paramMap);
            result.setTotal(count);
            result.setRows(itemsSumList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            result.setTotal(0);
            result.setRows(null);
        }
        return result;
    }

    /**
     * 查询单一科目分类汇总数据具体实现
     * @Title: queryJournalBaseItemsSumData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo queryJournalBaseItemsSumData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestParam = request.getParameter("requestParam");
        if (JSONUtil.isToJSONObject(requestParam)) {
            Map<String, Object> paramMap = JSON.parseObject(requestParam);
            if (paramMap.get("recordDate1") != null) {
                String recordDate = paramMap.get("recordDate1").toString();
                String days = recordDate.substring(recordDate.lastIndexOf("-"));
                String startDate = DateUtil.addOrCutDownForDay(Integer.parseInt(days));
                String endDate = DateUtil.getFormatDate(new Date());
                paramMap.put("startRecordDate", startDate);
                paramMap.put("endRecordDate", endDate);
            }
            if (paramMap.get("recordDate2") != null) {
                String recordDate = paramMap.get("recordDate2").toString();
                paramMap.put("recordDate", recordDate + "%");
            }
            try {
                Integer sumMoney = journalMapper.queryJournalBaseItemsSumInfo(paramMap);
                result.setData(sumMoney);
            } catch (Exception e) {
                result.setResult(false);
                result.setMessage("单一科目分类汇总数据查询失败，请联系管理员");
                result.setError(e.getMessage());
                log.error(e.getMessage());
            }
        }
        return result;
    }

    /**
     * 重算每月结余数据具体实现
     * @Title: rerunMonthlyBalanceData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo rerunMonthlyBalanceData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        try {
            JSONArray monthList = journalMapper.queryJournalBaseDateInfo(null);
            for (int m_i = 0, m_len = monthList.size() - 1; m_i < m_len; m_i++) {
                JSONObject oneMonth = monthList.getJSONObject(m_i);
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("record", oneMonth.getString("record"));
                JSONArray balanceList = journalMapper.queryLastMonthBalanceInfo(paramMap);
                for (int b_i = 0, b_len = balanceList.size(); b_i < b_len; b_i++) {
                    JSONObject oneBalance = balanceList.getJSONObject(b_i);
                    JournalBase journal = new JournalBase();
                    journal.setUnid(oneBalance.getString("record") + "_" + oneBalance.getString("accountCard") + "_结余信息");
                    journal.setType("income");
                    journal.setMoney(oneBalance.getBigDecimal("money"));
                    journal.setAccountCard(oneBalance.getString("accountCard"));

                    String recordDate = DateUtil.setMonthForJournal(oneBalance.getString("record"));
                    recordDate = recordDate.substring(0, 7);
                    journal.setRecordDate(recordDate);

                    journal.setContent("系统生成结余信息");
                    journal.setAddUser("管理员 : admin");
                    journal.setDomainCode("HAIYUAN");
                    journal.setApplicationCode("haiyuan");
                    journal.setStatus("3");

                    paramMap.clear();
                    paramMap.put("unid", journal.getUnid());
                    Integer balanceCount = journalMapper.queryJournalBaseInfoCount(paramMap);
                    if (balanceCount != 0) {
                        journal.setModifyTime(DateUtil.getFormatDateTime(new Date()));
                        Integer replace = journalMapper.updateJournalBaseInfoByUnid(journal);
                        if (replace == 1) {
                            result.setResult(true);
                            result.setMessage("月结信息更新成功，请刷新页面");
                        } else {
                            result.setResult(false);
                            result.setMessage("月结信息更新失败，请联系管理员");
                        }
                    } else {
                        journal.setSystemTime(DateUtil.getFormatDateTime(new Date()));
                        Integer add = journalMapper.addJournalBaseInfo(journal);
                        if (add == 1) {
                            result.setResult(true);
                            result.setMessage("月结信息生成成功，请刷新页面");
                        } else {
                            result.setResult(false);
                            result.setMessage("月结信息生成失败，请联系管理员");
                        }
                    }

                    Thread.sleep(500);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
